package com.nervenets.template.controller.user.params;

import com.alibaba.fastjson.JSONObject;
import com.nervenets.general.utils.StringUtils;
import com.nervenets.general.web.params.EntityPagingParams;
import com.nervenets.template.hibernate.domain.user.User;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;

import javax.persistence.criteria.*;
import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class UsersPagingParams extends EntityPagingParams<User> {
    @ApiModelProperty(value = "用户ID，不填不筛选")
    private long targetUserId;
    @ApiModelProperty(value = "用户昵称，不填不筛选")
    private String name;
    @ApiModelProperty(value = "用户电话，不填不筛选")
    private String mobile;
    @ApiModelProperty(value = "附加内容，JSON对象，key为字段，value为值，不填不筛选")
    private JSONObject extra;
    @ApiModelProperty(value = "关键词，不填不筛选")
    private String keyword;

    @Override
    public void generateSpecification(List<Predicate> predicates, Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        addEqualsPredicate(root.get("id"), targetUserId, targetUserId > 0);
        addOrLikePredicate(name, root.get("name"));
        addOrLikePredicate(mobile, root.get("mobile"));
        if (null != getExtra()) {
            getExtra().forEach((key, value) -> {
                if (!StringUtils.isEmpty(key) && null != value) {
                    final Join<Object, Object> extras = root.join("extras");
                    predicates.add(extras.on(
                            criteriaBuilder.equal(extras.get("field"), key),
                            criteriaBuilder.equal(extras.get("value"), value)
                    ).getOn());
                }
            });
        }
        addOrLikePredicate(keyword, root.get("name"), root.get("mobile"));
    }
}
